package com.simple.piger.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.simple.piger.entity.*;
import com.simple.piger.service.*;
import com.simple.piger.utils.AjaxResult;
import com.simple.piger.utils.PublicUtil;
import com.simple.piger.dto.resp.SysRoleListRespDto;
import com.simple.piger.dto.resp.SysUserListRespDto;
import com.simple.piger.utils.QiniuUpload;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 角色配置，超级管理员的接口类
 */
@Slf4j
@RestController
@RequestMapping("/cms/sysManage")
public class SystemController extends BaseController {
    @Autowired
    private CmsSysRoleService cmsSysRoleService;
    @Autowired
    private CmsSysPermissionService cmsSysPermissionService;
    @Autowired
    private CmsUserService cmsUserService;
    @Autowired
    private QiniuUpload qiniuUpload;
    @Autowired
    private ApplyUserService applyUserService;
    @Autowired
    private CmsSysRolePermissionService cmsSysRolePermissionService;
    @Autowired
    private InviteCompanyEmpService inviteCompanyEmpService;
     @Autowired
    private InviteCompanyJobService inviteCompanyJobService;
     @Autowired
    private InviteRecordService inviteRecordService;
    /**
     * 获取角色息配置列表页的分页信
     */
    @GetMapping("/getRoleList")
    public AjaxResult getRoleList(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        int total = cmsSysRoleService.getRoleListCount();
        List<SysRoleListRespDto> sysRoleListRespDtos = cmsSysRoleService.getRoleList(page, limit);
        return success(total, sysRoleListRespDtos);
    }

    /**
     * 获取权限信息的接口
     * @param id
     * @return
     */
    @GetMapping("/role/{id}")
    public AjaxResult getRole(@PathVariable("id") String id) {
        CmsSysRole role = cmsSysRoleService.selectById(id);
        SysRoleListRespDto respDto = new SysRoleListRespDto();
        BeanUtils.copyProperties(role, respDto);
        respDto.setRoleName(role.getName());
        return success(respDto);
    }
    /**
     * 删除角色信息
     */
    @PostMapping("/delRole/{id}")
    public AjaxResult delRole(@PathVariable Integer id) {
        String msg = cmsSysRoleService.delRoleById(id);
        return (msg == null) ? success() : fail(msg);
    }

    /**
     * 获取系统所有权限信息
     */
    @GetMapping("/getSysAllRights")
    public AjaxResult getSysAllRights() {
        return success(cmsSysPermissionService.getSysAllRights());
    }

    /**
     * 新增角色信息
     */
    @PostMapping("/addRole")
    public AjaxResult addRole(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        CmsSysRole cmsSysRole = JSONObject.toJavaObject(jsonObject, CmsSysRole.class);
        String[] rightsAdd = PublicUtil.splitStringList(jsonObject.getString("rights_add"));
        cmsSysRoleService.addRole(cmsSysRole, rightsAdd);
        return success();
    }

    /**
     * 修改角色信息
     */
    @PostMapping("/editRole")
    public AjaxResult editRole(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        CmsSysRole cmsSysRole = JSONObject.toJavaObject(jsonObject, CmsSysRole.class);
        String[] rightsAdd = PublicUtil.splitStringList(jsonObject.getString("rights_add"));
        String[] rightsDel = PublicUtil.splitStringList(jsonObject.getString("rights_del"));
        cmsSysRoleService.editRole(cmsSysRole, rightsAdd, rightsDel);
        return success();
    }

    /**
     * 根据角色主键获取角色信息和角色所拥有的权限信息
     */
    @GetMapping("/getRoleById/{id}")
    public AjaxResult getRoleById(@PathVariable Integer id) {
        // 获取角色信息
        CmsSysRole cmsSysRole = cmsSysRoleService.selectById(id);
        // 获取角色所拥有的模块、菜单和按钮权限
        JSONArray treeJson = cmsSysPermissionService.getRoleRigthsById(cmsSysRole.getId());
        // 构建返回数据
        LinkedHashMap<String, Object> rtn_map = new LinkedHashMap<>();
        rtn_map.put("role_info", cmsSysRole);
        rtn_map.put("role_permissions", treeJson);
        return success(rtn_map);
    }

    /**
     * 获取所有角色信息
     */
    @GetMapping("/getRoles")
    public AjaxResult getRoles(@RequestParam(name = "addEmpty", required = false) String addEmpry) {

        List<CmsSysRole> cmsSysRoles = cmsSysRoleService.selectList(new EntityWrapper<>());
        if (StringUtils.isNotBlank(addEmpry)) {
            CmsSysRole emppty = new CmsSysRole();
            emppty.setId(null);
            emppty.setName("请选择");
            cmsSysRoles.addAll(0, Lists.newArrayList(emppty));
        }
        return success(cmsSysRoles);
    }

    /**
     * 根据用户主键获取用户信息和用户所拥有的角色信息
     */
    @GetMapping("/user/info/{id}")
    public AjaxResult getUserById(@PathVariable("id") String id) {
        // 获取用户信息
        CmsSysUser cmsSysUser = cmsUserService.selectById(id);
        // 获取角色信息
        List<CmsSysRole> cmsSysRoles = cmsSysRoleService.getRoleListByUserId(id);
        // 构建返回数据
        LinkedHashMap<String, Object> rtn_map = new LinkedHashMap<>();
        rtn_map.put("user_info", cmsSysUser);
        rtn_map.put("user_roles", cmsSysRoles);
        return success(rtn_map);
    }

    /**
     * 获取帐号配置列表页的分页信息
     */
    @GetMapping("/getUserList")
    public AjaxResult getUserList(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        Integer roleId = jsonObject.getInteger("roleId");
        Boolean locked = jsonObject.getBoolean("locked");
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        int total = cmsUserService.getUserListCount(roleId, locked);
        List<SysUserListRespDto> sysUserListRespDtos = cmsUserService.getUserList(roleId, locked, page, limit);
        for (SysUserListRespDto sysUserListRespDto : sysUserListRespDtos) {
            // 获取角色信息
            List<CmsSysRole> cmsSysRoles = cmsSysRoleService.getRoleListByUserId(sysUserListRespDto.getId());
            StringBuilder stringBuilder = new StringBuilder();
            for (int i=0;i<cmsSysRoles.size();i++) {
                if ((i+1) == cmsSysRoles.size()) {
                    stringBuilder.append(cmsSysRoles.get(i).getName());
                } else {
                    stringBuilder.append(cmsSysRoles.get(i).getName()+"、");
                }
            }
            sysUserListRespDto.setRoleNames(stringBuilder.toString());
        }
        return success(total, sysUserListRespDtos);
    }

    /**
     * 启用帐号
     */
    @PostMapping("/user/{id}/unlock")
    public AjaxResult unlockUser(@PathVariable("id") String id) {
        // 获取用户信息
        CmsSysUser cmsSysUser = cmsUserService.selectById(id);
        cmsSysUser.setLocked(false);
        // 启用帐号
        Boolean bool = cmsUserService.updateById(cmsSysUser);
        return bool ? success() : fail("启用帐号失败！");
    }

    /**
     * 禁用帐号
     */
    @PostMapping("/user/{id}/lock")
    public AjaxResult lockUser(@PathVariable("id") String id) {
        // 获取用户信息
        CmsSysUser cmsSysUser = cmsUserService.selectById(id);
        cmsSysUser.setLocked(true);
        // 禁用帐号
        Boolean bool = cmsUserService.updateById(cmsSysUser);
        return bool ? success() : fail("禁用帐号失败！");
    }

    @Autowired
    private CmsSysUserRoleService cmsSysUserRoleService;
    /**
     * 删除账号
     */
    @PostMapping("/user/{id}/delete")
    public AjaxResult delete(@PathVariable("id") String id) {
        // 获取用户信息
        CmsSysUser cmsSysUser = cmsUserService.selectById(id);
        EntityWrapper<ApplyUser> auEw = new EntityWrapper<>();
        auEw.eq("cms_sys_user_id", cmsSysUser.getId());
        ApplyUser applyUser = applyUserService.selectOne(auEw);
        if ("1".equals(cmsSysUser.getId())) {
            return fail("超级管理员账号不允许删除");
        }
        if (null == applyUser) {
            return success();
        }
        EntityWrapper<InviteCompanyEmp> empEw = new EntityWrapper<>();
        empEw.eq("apply_user_id", applyUser.getId());
        InviteCompanyEmp emp = inviteCompanyEmpService.selectOne(empEw);

        EntityWrapper<CmsSysUserRole> roleEw = new EntityWrapper<>();
        roleEw.eq("user_id", id);
        List<CmsSysUserRole> roles = cmsSysUserRoleService.selectList(roleEw);

        EntityWrapper<InviteRecord> reEw = new EntityWrapper<>();
        reEw.eq("apply_user_id", applyUser.getId());
        List<InviteRecord> record = inviteRecordService.selectList(reEw);

        EntityWrapper<InviteCompanyJob> jobEw = new EntityWrapper<>();
        jobEw.eq("apply_user_id", applyUser.getId());
        List<InviteCompanyJob> job = inviteCompanyJobService.selectList(jobEw);
        if (null != applyUser) {
            applyUser.deleteById();
        }
        if (null != emp) {
            emp.deleteById();
        }
        if (null != cmsSysUser) {
            cmsSysUser.deleteById();
        }
        for (InviteRecord r : record) {
            r.deleteById();
        }
        for (InviteCompanyJob j : job) {
            j.deleteById();
        }
        for (CmsSysUserRole role : roles) {
            role.deleteById();
        }
        return success();
    }

    /**
     * 重置帐号密码
     */
    @PostMapping("/user/{id}/reset")
    public AjaxResult resetUserPwd(@PathVariable("id") String id) {
        cmsUserService.resetUserPwd(id);
        return success();
    }

    /**
     * 新增帐号信息
     */
    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        CmsSysUser cmsSysUser = JSONObject.toJavaObject(jsonObject, CmsSysUser.class);
        String[] userRolesAdd = PublicUtil.splitStringList(jsonObject.getString("user_roles_add"));
        String msg = cmsUserService.addUser(cmsSysUser, userRolesAdd);
        return (msg == null) ? success() : fail(msg);
    }

    /**
     * 修改帐号信息
     */
    @PostMapping("/editUser")
    public AjaxResult editUser(@RequestParam HashMap hashMap) {
        JSONObject jsonObject = PublicUtil.getJSONObject(hashMap);
        CmsSysUser cmsSysUser = JSONObject.toJavaObject(jsonObject, CmsSysUser.class);
        String[] userRolesAdd = PublicUtil.splitStringList(jsonObject.getString("user_roles_add"));
        String[] userRolesDel = PublicUtil.splitStringList(jsonObject.getString("user_roles_del"));
        String msg = cmsUserService.editUser(cmsSysUser, userRolesAdd, userRolesDel);
        return (msg == null) ? success() : fail(msg);
    }

    /**
     * 七牛文件上传凭证
     */
    @GetMapping("/fileToken")
    public JSONObject getFileToken(){
        String token = qiniuUpload.getFileToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uptoken", token);
        return jsonObject;
    }
}
